
package com.sven.sharedb.core.message;

import com.sven.sharedb.core.utils.CommonUtils;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sven.wang
 * @version 2022/4/26 17:57
 */
public class ObjectRestResponse<T> extends BaseResponse {

    T data;
    //成功状态 ：200（默认，表示业务正常）
    public static final int STATUS_SUCCESS = 200;
    //服务器错误
    public static final int STATUS_FAIL = 500;
    //400（业务错误）
    public static final int STATUS_ERROR_BIZ = 400;

    public ObjectRestResponse () {

    }

    public ObjectRestResponse (int status, String message) {
        super(status, message);
    }


    public ObjectRestResponse (int status,String message, T data) {
        super.setStatus(status);
        super.setMessage(message);
        this.setData(data);
    }

    public static <T> ObjectRestResponse<T> success(T data) {
        return new ObjectRestResponse<T>(STATUS_SUCCESS, HttpStatus.OK.name(), data);
    }

    public static <T> ObjectRestResponse<T> error(String message) {
        return new ObjectRestResponse<>(STATUS_ERROR_BIZ, message, null);
    }

    public static <T> ObjectRestResponse<T> error(int status, String message) {
        return new ObjectRestResponse<T>(status, message);
    }

    public ObjectRestResponse data(T data) {
        this.setData(data);
        return this;
    }

    public T getData() {
        return data;
    }

    public T checkAndGetData() {
        CommonUtils.dealResponse(this);
        return data;
    }


    /**
     * 转为map返回类型（仅适用于返回对象为map，但未显式定义的ObjectRestResponse对象）
     * @param response 响应结果
     */
    public static ObjectRestResponse<Map<String, Object>> toMapResponse(ObjectRestResponse response) {
        ObjectRestResponse<Map<String, Object>> restResponse = new ObjectRestResponse<>();
        if (response == null) {
            restResponse.setStatus(ObjectRestResponse.STATUS_FAIL);
            return restResponse;
        }

        Map<String, Object> result;
        if (null == response.getData()) {
            result = new HashMap<>();
        } else {
            result = (Map<String, Object>) response.getData();
        }
        restResponse.setStatus(response.getStatus());
        restResponse.setMessage(response.getMessage());
        restResponse.setData(result);
        return restResponse;
    }

    public void setData(T data) {
        this.data = data;
    }


}
